package com.efast.dmom.mes.service.impl;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.efast.dmom.mes.bean.ResultBean;
import com.efast.dmom.mes.bean.WmsInOutWarehouseLog;
import com.efast.dmom.mes.bean.WmsInWarehouseOrder;
import com.efast.dmom.mes.bean.WmsOrderLog;
import com.efast.dmom.mes.bean.WmsPurchaseOrder;
import com.efast.dmom.mes.bean.WmsStorage;
import com.efast.dmom.mes.dao.entity.PartDao;
import com.efast.dmom.mes.dao.entity.WmsInOutWarehouseLogDao;
import com.efast.dmom.mes.dao.entity.WmsInWarehouseOrderDao;
import com.efast.dmom.mes.dao.entity.WmsOrderLogDao;
import com.efast.dmom.mes.dao.entity.WmsPurchaseOrderDao;
import com.efast.dmom.mes.dao.entity.WmsStorageDao;
import com.efast.dmom.mes.entity.PartEntity;
import com.efast.dmom.mes.entity.WmsWarehouseBasEntity;
import com.efast.dmom.mes.service.WmsInWarehouseOrderService;
import com.efast.dmom.mes.util.ServiceBaseEntityUtil;
import com.efast.dmom.mes.util.SpringWebUtils;
import com.efast.dmom.mes.util.TimeUtil;
import com.efast.dmom.mes.util.WmsOrderLogStatus;
import com.efast.dmom.mes.util.WmsOrderStatusUtil;

@Service
@Transactional
public class WmsInWarehouseOrderServiceImpl implements WmsInWarehouseOrderService {

	@Autowired
	private WmsInWarehouseOrderDao wmsInWarehouseOrderDao;

	@Autowired
	private WmsPurchaseOrderDao wmsPurchaseOrderDao;

	@Autowired
	private ServiceBaseEntityUtil serviceBaseEntityUtil;

	@Autowired
	private WmsOrderLogDao wmsOrderLogDao;

	@Autowired
	private WmsStorageDao wmsStorageDao;

	@Autowired
	private WmsInOutWarehouseLogDao wmsInOutWarehouseLogDao;
	
	@Autowired
	private PartDao partDao;
	
	

	@Override
	public ResultBean batchSave(List<WmsInWarehouseOrder> wmsInWarehouseOrder) {
		ResultBean resultBean = new ResultBean(true);
		List<WmsOrderLog> list = new ArrayList<WmsOrderLog>();
		String no = serviceBaseEntityUtil.getNo("RKD_code");
		wmsInWarehouseOrder.forEach(item -> {
			item.setInWarehouseOrder(no);
			item.setInWarehouseStatus(WmsOrderStatusUtil.NOCONFIRM);
			item.setTotalWeight(item.getUnitWeight() * item.getUnitPrice());
			ServiceBaseEntityUtil.setSaveBaseEntityData(item);
			item.setTotalWeight(item.getInWarehouseQuality() * item.getUnitWeight());
		});
		// 保存入库单信息
		wmsInWarehouseOrderDao.batchSave(wmsInWarehouseOrder);

		wmsInWarehouseOrder.forEach(item -> {
			WmsOrderLog wmsOrderLog = new WmsOrderLog();
			ServiceBaseEntityUtil.setSaveBaseEntityData(item);
			ServiceBaseEntityUtil.setSaveBaseEntityData(wmsOrderLog);
			wmsOrderLog.setOrderNo(no);
			wmsOrderLog.setOrderOperationStatus(WmsOrderLogStatus.ADD.getOperation());
			wmsOrderLog.setOrderId(item.getId());
			list.add(wmsOrderLog);
		});
		// 保存入库单日志信息
		wmsOrderLogDao.batchSave(list);
		return resultBean;
	}

	@Override
	public ResultBean update(WmsInWarehouseOrder wmsInWarehouseOrder) {
		ResultBean resultBean = new ResultBean(true);
		// 查询入库单单号下是否存在相同的物料
		WmsInWarehouseOrder wmsInWarehouseOrder2 = new WmsInWarehouseOrder();
		wmsInWarehouseOrder2.setInWarehouseOrder(wmsInWarehouseOrder.getInWarehouseOrder());
		wmsInWarehouseOrder2.setId(wmsInWarehouseOrder.getId());
		List<WmsInWarehouseOrder> selectByNo = wmsInWarehouseOrderDao.selectByNo(wmsInWarehouseOrder2);
		if (selectByNo.size() > 0) {
			for (WmsInWarehouseOrder wmsInWarehouseOrder3 : selectByNo) {
				if (wmsInWarehouseOrder3.getPartId() == wmsInWarehouseOrder.getPartId()
						&& wmsInWarehouseOrder3.getWarehouseId() == wmsInWarehouseOrder.getWarehouseId()) {
					resultBean.setErrorMessage("当前仓库存在重复物料，请检查数据！");
					return resultBean;
				}
			}
			if (!selectByNo.get(0).getInWarehouseType().equals(wmsInWarehouseOrder.getInWarehouseType())) {
				resultBean.setErrorMessage("入库类型必须为/" + selectByNo.get(0).getInWarehouseType() + "/请检查！");
				return resultBean;
			}
		}
		ServiceBaseEntityUtil.setUpdateBaseEntityData(wmsInWarehouseOrder);
		WmsOrderLog wmsOrderLog = new WmsOrderLog();
		ServiceBaseEntityUtil.setSaveBaseEntityData(wmsOrderLog);
		wmsOrderLog.setOrderNo(wmsInWarehouseOrder.getInWarehouseOrder());
		wmsOrderLog.setOrderOperationStatus(WmsOrderLogStatus.UPDATE.getOperation());
		wmsOrderLog.setOrderId(wmsInWarehouseOrder.getId());
		// 保存编辑入库信息
		wmsOrderLogDao.save(wmsOrderLog);
		// 更新总重量
		wmsInWarehouseOrder.setTotalWeight(wmsInWarehouseOrder.getInWarehouseQuality() * wmsInWarehouseOrder.getUnitWeight());
		// 保存更新数据
		wmsInWarehouseOrderDao.update(wmsInWarehouseOrder);
		return resultBean;
	}

	@Override
	public ResultBean batchDelete(List<WmsInWarehouseOrder> list) {
		ResultBean resultBean = new ResultBean(true);
		List<WmsOrderLog> logList = new ArrayList<WmsOrderLog>();
		list.forEach(item -> {
			WmsOrderLog wmsOrderLog = new WmsOrderLog();
			ServiceBaseEntityUtil.setSaveBaseEntityData(item);
			ServiceBaseEntityUtil.setSaveBaseEntityData(wmsOrderLog);
			wmsOrderLog.setOrderNo(item.getInWarehouseOrder());
			wmsOrderLog.setOrderOperationStatus(WmsOrderLogStatus.DELETE.getOperation());
			wmsOrderLog.setOrderId(item.getId());
			logList.add(wmsOrderLog);
		});
		// 批量删除入库信息
		wmsInWarehouseOrderDao.batchDelete(list);
		// 批量保存日志信息
		wmsOrderLogDao.batchSave(logList);
		return resultBean;
	}

	@Override
	public ResultBean batchConfirm(List<WmsInWarehouseOrder> wmsInWarehouseOrder) {

		ResultBean resultBean = new ResultBean(true);
		List<WmsInWarehouseOrder> list = wmsInWarehouseOrderDao.selectByNos(wmsInWarehouseOrder);
		List<WmsOrderLog> logList = new ArrayList<WmsOrderLog>();
		List<WmsInWarehouseOrder> list1 = new ArrayList<WmsInWarehouseOrder>();
		list.forEach(item -> {
			WmsOrderLog wmsOrderLog = new WmsOrderLog();
			ServiceBaseEntityUtil.setSaveBaseEntityData(item);
			item.setInWarehouseStatus(WmsOrderStatusUtil.CONFIRM);
			item.setInWarehouseTime(TimeUtil.getLocalDateTime());
			ServiceBaseEntityUtil.setSaveBaseEntityData(wmsOrderLog);
			wmsOrderLog.setOrderNo(item.getInWarehouseOrder());
			wmsOrderLog.setOrderOperationStatus(WmsOrderLogStatus.CONFIRM.getOperation());
			wmsOrderLog.setOrderId(item.getId());
			logList.add(wmsOrderLog);
			if (item.getInWarehouseType().equals("采购")) {
				list1.add(item);
			}
		});
		// 入库单日志
		wmsOrderLogDao.batchSave(logList);
		// 入库单确认信息保存
		wmsInWarehouseOrderDao.batchConfirm(list);

		if (list1.size()>0) {
			// 更新采购单数据
			checkPurchaseOrderQualityAndStatus(list);
		}
		// 更新入库是库存数据，并记录入库历史信息
		try {
			list.forEach(item -> {
				item.setTotalWeight(item.getInWarehouseQuality()* item.getUnitWeight());
			});
			updateStorageQuality(list);
		} catch (RuntimeException e) {
			throw new RuntimeException(e.getMessage());
		}

		return resultBean;
	}

	public void checkPurchaseOrderQualityAndStatus(List<WmsInWarehouseOrder> list) {
		List<WmsPurchaseOrder> datas = new ArrayList<WmsPurchaseOrder>();
		if (list.size() > 0) {
			list.forEach(item -> {
				WmsPurchaseOrder wmsPurchaseOrder = new WmsPurchaseOrder();
				wmsPurchaseOrder.setPartId(item.getPartId());
				wmsPurchaseOrder.setPurchaseOrderNo(item.getRelationOrderNo());
				datas.add(wmsPurchaseOrder);
			});
			List<WmsPurchaseOrder> dataByPurchaseNo = wmsPurchaseOrderDao.getDataByPurchaseNo(datas);
			if (dataByPurchaseNo.size() > 0) {
				for (WmsPurchaseOrder wmsPurchaseOrder : dataByPurchaseNo) {
					for (WmsInWarehouseOrder wmsInWarehouseOrder : list) {
						if (wmsPurchaseOrder.getPurchaseOrderNo().equals(wmsInWarehouseOrder.getRelationOrderNo())
								&& wmsPurchaseOrder.getPartId() == wmsInWarehouseOrder.getPartId()) {
							wmsPurchaseOrder.setArrivedQuantity(
									wmsPurchaseOrder.getArrivedQuantity() + Integer.parseInt(new DecimalFormat("0")
											.format(wmsInWarehouseOrder.getInWarehouseQuality())));
							wmsPurchaseOrder.setNoArrivedQuantity(
									wmsPurchaseOrder.getNoArrivedQuantity() - Integer.parseInt(new DecimalFormat("0")
											.format(wmsInWarehouseOrder.getInWarehouseQuality())));
						}
					}
				}
				for (WmsPurchaseOrder wmsPurchaseOrder : dataByPurchaseNo) {
					if (wmsPurchaseOrder.getArrivedQuantity() >= wmsPurchaseOrder.getPlanQuantity()) {
						wmsPurchaseOrder.setStatus(WmsOrderStatusUtil.COMPLETE);
					} else {
						wmsPurchaseOrder.setStatus(WmsOrderStatusUtil.CONFIRM);
					}
				}
				wmsPurchaseOrderDao.batchUpdateInWarehouse(dataByPurchaseNo);
			}
		}
	}

	// 更新入库是库存数据，并记录入库历史信息
	public void updateStorageQuality(List<WmsInWarehouseOrder> list) {
		if (list.size() > 0) {
			for (WmsInWarehouseOrder wmsInWarehouseOrder : list) {
				WmsStorage wmsStorage = new WmsStorage();
				wmsStorage.setWarehouseBasId(wmsInWarehouseOrder.getWarehouseId());
				wmsStorage.setPartId(wmsInWarehouseOrder.getPartId());
				// 查询库存表中是否存在数据
				double unitPrice = 0;
				double inWarehouseQuality = 0;
				List<WmsStorage> selectByWarehouseAndPart = wmsStorageDao.selectByWarehouseAndPart(wmsStorage);
				// 查询入库单对应的仓库
				WmsWarehouseBasEntity warehouseBasEntity = wmsStorageDao.getById(wmsInWarehouseOrder.getWarehouseId());
				unitPrice = wmsInWarehouseOrder.getUnitPrice();
				inWarehouseQuality = wmsInWarehouseOrder.getInWarehouseQuality();
				PartEntity partEntity = partDao.getById(wmsInWarehouseOrder.getPartId());
				// 库存存在
				if (selectByWarehouseAndPart.size() == 1) {
					
					// 更新库存数据
					WmsStorage wmsStorage2 = selectByWarehouseAndPart.get(0);
					// 计算总入库的物料的总金额
					unitPrice = wmsInWarehouseOrder.getUnitPrice();
					inWarehouseQuality = wmsInWarehouseOrder.getInWarehouseQuality();
					wmsStorage2.setTotalAmount(wmsStorage2.getTotalAmount() + unitPrice * inWarehouseQuality);
					// 当为外协仓库时，库存重量为数量乘以单位重量
					if (wmsInWarehouseOrder.getInWarehouseType().equals("委外") && partEntity.getIsWeightUnit().equals("是")) {
						wmsStorage2.setTotalWeight(wmsStorage2.getTotalWeight() + wmsInWarehouseOrder.getTotalWeight());
					}
					wmsStorage2.setStorageQuality(
							wmsStorage2.getStorageQuality() + wmsInWarehouseOrder.getInWarehouseQuality());
					// 更新时间
					wmsStorage2.setLastUpdateTime(TimeUtil.getLocalDateTime());
					wmsStorage2.setLastUpdateUser(SpringWebUtils.getRequestUser());
					wmsStorageDao.updateQuality(wmsStorage2);
					// 创建出入库历史
					createInAndOutWarehouseLog(wmsInWarehouseOrder);
				} else if (selectByWarehouseAndPart.size() == 0) {
					// 保存库存数据
					double unitPrice1 = wmsInWarehouseOrder.getUnitPrice();
					double inWarehouseQuality1 = wmsInWarehouseOrder.getInWarehouseQuality();
					// 计算总入库的物料的总金额
					wmsStorage.setTotalAmount(unitPrice1 * inWarehouseQuality1);
					wmsStorage.setCreateTime(TimeUtil.getLocalDateTime());
					wmsStorage.setCreateUser(SpringWebUtils.getRequestUser());
					wmsStorage.setCompanyCode(SpringWebUtils.getRequestCompany());
					wmsStorage.setUnit(wmsInWarehouseOrder.getInWarehouseUnit());
					if (warehouseBasEntity.getWarehouseType().equals("外协仓库")) {
						wmsStorage.setTotalWeight(wmsInWarehouseOrder.getTotalWeight());
					}
					wmsStorage.setStorageQuality(wmsInWarehouseOrder.getInWarehouseQuality());
					wmsStorageDao.save(wmsStorage);
					// 创建出入库历史
					createInAndOutWarehouseLog(wmsInWarehouseOrder);
				}
				// 当为外协仓库时数量反冲仓库数据
				PartEntity byId = partDao.getById(wmsInWarehouseOrder.getToPartId());
				if (wmsInWarehouseOrder.getInWarehouseType().equals("委外") && byId.getIsWeightUnit().equals("是")) {
					wmsInWarehouseOrder.setPartNo(byId.getPartNo());
					if (!byId.getIsWeightUnit().equals("是")) {
						throw new RuntimeException("当前反冲物料必须为重量单位物料！");
					}
					// 查询需要反冲的仓库的库存
					WmsStorage wmsStorage1 = new WmsStorage();
					wmsStorage1.setWarehouseNo(wmsInWarehouseOrder.getToWarehouseNo());
					wmsStorage1.setPartId(wmsInWarehouseOrder.getToPartId());
					List<WmsStorage> selectByWarehouseNoAndPart = wmsStorageDao.selectByWarehouseNoAndPart(wmsStorage1);
					if (selectByWarehouseNoAndPart.size() == 1) {
						WmsStorage wmsStorage2 = selectByWarehouseNoAndPart.get(0);
						if (wmsStorage2.getTotalAmount() - unitPrice * inWarehouseQuality < 0) {
							throw new RuntimeException("委外单据反冲扣减库存物料总金额不足，请检查！");
						}
						wmsStorage2.setTotalAmount(wmsStorage2.getTotalAmount() - unitPrice * inWarehouseQuality);
						if (wmsStorage2.getStorageQuality() - wmsInWarehouseOrder.getInWarehouseQuality() < 0) {
							throw new RuntimeException("委外单据反冲扣减库存物料总数量不足，请检查！");
						}
						wmsStorage2.setStorageQuality(
								wmsStorage2.getStorageQuality() - wmsInWarehouseOrder.getInWarehouseQuality());
						wmsStorage2.setTotalWeight(wmsStorage2.getTotalWeight() - wmsInWarehouseOrder.getTotalWeight());
						if (wmsStorage2.getTotalWeight()<0) {
							throw new RuntimeException("委外单据反冲扣减库存总重量不足，请检查！");
						}
						// 更新时间
						wmsStorage2.setLastUpdateTime(TimeUtil.getLocalDateTime());
						wmsStorage2.setLastUpdateUser(SpringWebUtils.getRequestUser());
						wmsStorageDao.updateData(wmsStorage2);
						
						
						WmsInWarehouseOrder wmsInWarehouseOrder2 = new WmsInWarehouseOrder();
						Integer selectIdByNo = wmsStorageDao.selectIdByNo(wmsInWarehouseOrder.getToWarehouseNo());
						wmsInWarehouseOrder2.setWarehouseId(selectIdByNo);
						wmsInWarehouseOrder2.setInWarehouseOrder(wmsInWarehouseOrder.getInWarehouseOrder());
						wmsInWarehouseOrder2.setPartId(wmsInWarehouseOrder.getToPartId());
						wmsInWarehouseOrder2.setInWarehouseUnit(wmsInWarehouseOrder.getInWarehouseUnit());
						wmsInWarehouseOrder2.setUnitPrice(wmsInWarehouseOrder.getUnitPrice());
						wmsInWarehouseOrder2.setRemark(wmsInWarehouseOrder.getRemark());
						wmsInWarehouseOrder2.setInWarehouseQuality(wmsInWarehouseOrder.getInWarehouseQuality());
						createInAndOutWarehouseLog(wmsInWarehouseOrder);
					} else if (selectByWarehouseNoAndPart.size() == 0) {
						throw new RuntimeException("当前仓库" + wmsInWarehouseOrder.getToWarehouseNo() + "当前物料"
								+ wmsInWarehouseOrder.getPartNo() + "反冲扣减库存不足！");
					} else {
						throw new RuntimeException("物料  "+wmsInWarehouseOrder.getPartNo()+"  查询出多个仓库，查询出错！");
					}
				}
			}
		}

	}

	// 创建出入库历史
	public void createInAndOutWarehouseLog(WmsInWarehouseOrder wmsInWarehouseOrder) {
		WmsInOutWarehouseLog wmsInOutWarehouseLog = new WmsInOutWarehouseLog();
		wmsInOutWarehouseLog.setCompanyCode(SpringWebUtils.getRequestCompany());
		wmsInOutWarehouseLog.setCreateTime(TimeUtil.getLocalDateTime());
		wmsInOutWarehouseLog.setCreateUser(SpringWebUtils.getRequestUser());
		wmsInOutWarehouseLog.setInOutWarehouseId(wmsInWarehouseOrder.getId());
		wmsInOutWarehouseLog.setInOutWarehouseNo(wmsInWarehouseOrder.getInWarehouseOrder());
		wmsInOutWarehouseLog.setWarehouseId(wmsInWarehouseOrder.getWarehouseId());
		wmsInOutWarehouseLog.setOperation(WmsOrderStatusUtil.INWAREHOUSE);
		wmsInOutWarehouseLog.setPartId(wmsInWarehouseOrder.getPartId());
		wmsInOutWarehouseLog.setUnit(wmsInWarehouseOrder.getInWarehouseUnit());
		wmsInOutWarehouseLog.setUnitPrice(wmsInWarehouseOrder.getUnitPrice());
		wmsInOutWarehouseLog.setInOutWarehouseRemark(wmsInWarehouseOrder.getRemark());
		wmsInOutWarehouseLog.setInOutWarehouseQuality(wmsInWarehouseOrder.getInWarehouseQuality());
		wmsInOutWarehouseLogDao.save(wmsInOutWarehouseLog);
	}

	@Override
	public ResultBean save(WmsInWarehouseOrder wmsInWarehouseOrder) {
		ResultBean resultBean = new ResultBean(true);
		// 查询当前选中的单据编码下所有的数据
		List<WmsInWarehouseOrder> selectByNos = wmsInWarehouseOrderDao.selectByNo(wmsInWarehouseOrder);
		if (selectByNos.size() > 0) {
			for (WmsInWarehouseOrder wmsInWarehouseOrder2 : selectByNos) {
				if (wmsInWarehouseOrder2.getPartId() == wmsInWarehouseOrder.getPartId()
						&& wmsInWarehouseOrder2.getWarehouseId() == wmsInWarehouseOrder.getWarehouseId()) {
					resultBean.setErrorMessage("当前仓库已存在当前物料，请检查！");
					return resultBean;
				}
			}
			if (!selectByNos.get(0).getInWarehouseType().equals(wmsInWarehouseOrder.getInWarehouseType())) {
				resultBean.setErrorMessage("入库类型必须为/" + selectByNos.get(0).getInWarehouseType() + "/请检查！");
				return resultBean;
			}
		}
		ServiceBaseEntityUtil.setSaveBaseEntityData(wmsInWarehouseOrder);
		wmsInWarehouseOrder.setInWarehouseStatus(WmsOrderStatusUtil.NOCONFIRM);
		int save = wmsInWarehouseOrderDao.save(wmsInWarehouseOrder);
		if (save == 1) {
			WmsOrderLog wmsOrderLog = new WmsOrderLog();
			ServiceBaseEntityUtil.setUpdateLogEntityData(wmsOrderLog);
			wmsOrderLog.setOrderNo(wmsInWarehouseOrder.getInWarehouseOrder());
			wmsOrderLog.setOrderOperationStatus(WmsOrderLogStatus.ADD.getOperation());
			wmsOrderLog.setOrderId(wmsInWarehouseOrder.getId());
			wmsOrderLogDao.save(wmsOrderLog);
		}
		return resultBean;
	}

	@Override
	public ResultBean deleteByNos(List<WmsInWarehouseOrder> wmsInWarehouseOrder) {
		ResultBean resultBean = new ResultBean(true);
		// 查询当前选中的单据编码下所有的数据
		List<WmsInWarehouseOrder> selectByNos = wmsInWarehouseOrderDao.selectByNos(wmsInWarehouseOrder);
		if (selectByNos.size() > 0) {
			List<WmsOrderLog> logList = new ArrayList<WmsOrderLog>();
			for (WmsInWarehouseOrder wmsInWarehouseOrder2 : selectByNos) {
				WmsOrderLog wmsOrderLog = new WmsOrderLog();
				ServiceBaseEntityUtil.setSaveBaseEntityData(wmsOrderLog);
				wmsOrderLog.setOrderNo(wmsInWarehouseOrder2.getInWarehouseOrder());
				wmsOrderLog.setOrderOperationStatus(WmsOrderLogStatus.DELETE.getOperation());
				wmsOrderLog.setOrderId(wmsInWarehouseOrder2.getId());
				logList.add(wmsOrderLog);
			}

			// 删除当前选中的单据编码下所有的数据
			wmsInWarehouseOrderDao.deleteByNos(wmsInWarehouseOrder);

			// 保存操作日志
			wmsOrderLogDao.batchSave(logList);

		}
		return resultBean;
	}

}
